package besta.moon.sql.expression.function.string;

import java.io.ByteArrayOutputStream;

import besta.moon.metadata.MoonResultSetMetaData;
import besta.moon.sql.expression.function.FunctionReturnP1StringAndBinary;
import besta.moon.sql.parser.SQLTokenizer;

public class FunctionRepeat extends FunctionReturnP1StringAndBinary {

    @Override
    public final int getFunction() {
        return SQLTokenizer.REPEAT;
    }

    @Override
    public final byte[] getBytes() throws Exception {
        if (isNull()) {
            return null;
        }
        byte[] bytes = param1.getBytes();
        int count = param2.getInt();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        for (int i = 0; i < count; i++) {
            buffer.write(bytes);
        }
        return buffer.toByteArray();
    }

    @Override
    public final String getString() throws Exception {
        if (isNull()) {
            return null;
        }
        String str = param1.getString();
        int count = param2.getInt();
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < count; i++) {
            buffer.append(str);
        }
        return buffer.toString();
    }

    @Override
    public int getPrecision() {
        return MoonResultSetMetaData.getDataTypePrecision(getDataType(), -1);
    }

}
